<template>
  <div class="app-container">

    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px" style="margin-bottom: 5px">
      <div class="con-container">
        <div class="lab-container">
          <label class="condition-item-title"></label>
        </div>
        <div class="btn-container">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">刷新</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['wyfw:building:add']">新增
            </el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>

    <el-table ref="table" v-loading="loading" :lazy="true" :load="buildingListLoad" :data="buildingList" row-key="id" :expand-row-keys="expand" :height="tableHeight" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="名称" header-align="center" align="left" prop="buildingName" min-width="400" show-overflow-tooltip>
        <template v-slot="scope">
          <svg-icon v-if="scope.row.buildingType === 0 || scope.row.buildingType === '0'"  class-name="treeIconOther" icon-class="nhgk_park"></svg-icon>
          <svg-icon v-if="scope.row.buildingType === 1 || scope.row.buildingType === '1'"  class-name="treeIconOther" icon-class="nhgk_building"></svg-icon>
          <svg-icon v-if="scope.row.buildingType === 2 || scope.row.buildingType === '2'"  class-name="treeIconOther" icon-class="nhgk_unit"></svg-icon>
          <svg-icon v-if="scope.row.buildingType === 3 || scope.row.buildingType === '3'"  class-name="treeIconOther" icon-class="nhgk_floor"></svg-icon>
          <svg-icon v-if="scope.row.buildingType === 4 || scope.row.buildingType === '4'"  class-name="treeIconOther" icon-class="nhgk_room"></svg-icon>
          <span style="margin-left: 5px">{{ scope.row.buildingName }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" label="建筑面积(m²)" align="left" prop="aream" :formatter="pointTwo"/>
      <el-table-column label="类型" align="center" prop="buildingType">
        <template v-slot="scope">
          <dict-tag :options="dict.type.building_type" :value="scope.row.buildingType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="buildingStatus">
        <template v-slot="scope">
          <dict-tag :options="dict.type.building_status" :value="scope.row.buildingStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" align="left" class-name="small-padding fixed-width" width="190">
        <template v-slot="scope">
          <el-button v-if="scope.row.buildingType != 0" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['wyfw:building:edit']">修改</el-button>
          <el-button v-if="scope.row.buildingType != 4" size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)" v-hasPermi="['wyfw:building:edit']">新增</el-button>
<!--          <el-button v-if="scope.row.buildingType != 0" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-show="!loginUserBuildingId||loginUserBuildingId!==scope.row.id" v-hasPermi="['wyfw:building:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增或修改建筑信息对话框 -->
    <el-dialog :visible.sync="open" @close="dialogClose" :close-on-click-modal="false" class="customForm" :class="dialogClassType">
      <div slot="title">
        <span><i :class="dialogIcon"></i></span>
        <span> {{ title }}</span>
      </div>
      <div class="building-body"></div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <div class="sub-project">
          <div class="sub-title">
            <div class="sub-title-name">基本信息</div>
          </div>
          <div class="sub-body">
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="buildingName" v-if="!readOnly">
                  <el-input v-model="form.buildingName" placeholder="请输入名称"/>
                </el-form-item>
                <el-form-item label="名称：" prop="buildingName" v-if="readOnly" class="custom-form-item">
                  {{ form.buildingName }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="建筑面积(m²)" prop="aream" v-if="!readOnly">
                  <el-input  v-model="form.aream" placeholder="请输入建筑面积"/>
                </el-form-item>
                <el-form-item label="建筑面积(m²)：" prop="aream" v-if="readOnly" class="custom-form-item">
                  {{ form.aream }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="类型" prop="buildingType" v-if="!readOnly" >
                  <el-select @change="$forceUpdate" v-model="form.buildingType" placeholder="请选择类型" class="customSelect form-item" style="width: 91%">
                    <el-option
                      v-for="dictItem in dict.type.building_type"
                      :key="dictItem.value"
                      :label="dictItem.label"
                      :value="dictItem.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="类型：" prop="buildingType" v-if="readOnly" class="custom-form-item" >
                  <dict-tag :options="dict.type.building_type" :value="form.buildingType"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上级建筑" prop="parentId" v-if="!readOnly" class="custom-form-item">
                  <treeselect v-model="form.parentId" :options="buildingOptions" :normalizer="normalizer" :show-count="true" placeholder="选择上级建筑"/>
                </el-form-item>
                <el-form-item label="上级建筑：" prop="parentId" v-if="readOnly" class="custom-form-item">
                  {{ parentIdFormatter(form.parentId) }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="物业联系人" prop="principal" v-if="!readOnly">
                  <el-input v-model="form.principal" placeholder="请输入物业联系人"/>
                </el-form-item>
                <el-form-item label="物业联系人：" prop="principal" v-if="readOnly" class="custom-form-item">
                  {{ form.principal }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物业联系方式" prop="principalContactInfo" v-if="!readOnly">
                  <el-input  v-model="form.principalContactInfo" placeholder="请输入物业联系方式"/>
                </el-form-item>
                <el-form-item label="物业联系方式：" prop="principalContactInfo" v-if="readOnly" class="custom-form-item">
                  {{ form.principalContactInfo }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="状态" prop="buildingStatus" v-if="!readOnly" >
                  <el-select v-model="form.buildingStatus" placeholder="请选择状态" style="width: 91%" class="customSelect form-item">
                    <el-option
                      v-for="dictItem in dict.type.building_status" :key="dictItem.value" :label="dictItem.label" :value="dictItem.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="状态：" prop="buildingStatus" v-if="readOnly" class="custom-form-item">
                  <dict-tag :options="dict.type.building_status" :value="scope.row.buildingStatus"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="显示顺序" prop="orderNum" v-if="!readOnly"  >
                  <el-input-number v-model="form.orderNum" class="form-item" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="显示顺序：" prop="orderNum" v-if="readOnly" class="custom-form-item">
                  {{ form.orderNum }}
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="form.buildingType === '4' ">
                <el-form-item label="房屋占比(%)" prop="housePercent" v-if="!readOnly">
                  <el-input-number class="form-item" :precision=2 :min=0 :max=100 v-model="form.housePercent" :step=0.01 >
                  </el-input-number>
                </el-form-item>
                <el-form-item label="房屋占比(%)：" prop="housePercent" v-if="readOnly" class="custom-form-item">
                  {{ form.housePercent }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在位置" prop="location" v-if="!readOnly">
                  <el-input  v-model="form.location" placeholder="请输入所在位置"/>
                </el-form-item>
                <el-form-item label="所在位置：" prop="location" v-if="readOnly" class="custom-form-item">
                  {{ form.location }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经度" prop="lon" v-if="!readOnly">
                  <el-input v-model="form.lon" placeholder="请输入经度"/>
                </el-form-item>
                <el-form-item label="经度：" prop="lon" v-if="readOnly" class="custom-form-item">
                  {{ form.lon }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="lat" v-if="!readOnly">
                  <el-input  v-model="form.lat" placeholder="请输入纬度"/>
                </el-form-item>
                <el-form-item label="纬度：" prop="lat" v-if="readOnly" class="custom-form-item">
                  {{ form.lat }}
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="sub-project" v-if="operationType===3&& deviceList.length>0">
          <div class="sub-title">
            <div class="sub-title-name">设备列表</div>
          </div>
          <div class="sub-body">
            <el-table v-loading="loading" :data="deviceList">
              <el-table-column label="序号" type="index" width="55" align="left">
                <template v-slot="scope">
                  <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="设备名称" align="center" prop="deviceName"/>
              <el-table-column label="设备类型" align="center" prop="deviceType"  :formatter="typeFormatter"/>
              <el-table-column label="设备状态" align="center" prop="deviceStatus">
                <template v-slot="scope">
                  <dict-tag :options="dict.type.device_status" :value="scope.row.deviceStatus"/>
                </template>
              </el-table-column>
              <el-table-column label="使用状态" align="center" prop="useState">
                <template v-slot="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.useState"/>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="operationType !== 3">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="operationType === 3">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBuilding, getBuilding, delBuilding, addBuilding, updateBuilding} from "@/api/components/building/building"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";




export default {
  name: "Building",
  dicts: ['building_type', 'building_status','sys_normal_disable','device_status'],
  components: {Treeselect},
  data() {
    return {
      tableOffset: 155,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      readOnly: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      tableHeight: 450,
      // 建筑信息表格数据
      buildingList: [],
      dialogClassType:'_baseForm_big',
      operationType: 1,  //操作类型，1=新增，2=编辑，3=详情
      dialogIcon: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      parentId:undefined,
      //类型显示标志
      typeFlag:false,
      //状态显示标志
      statusFlag:false,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        buildingNo: null,
        buildingName: null,
        parentId: null,
        floorHeight: null,
        buildingType: null,
        buildingStatus: null,
        principal: null,
        principalContactInfo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "建筑上级不能为空", trigger: "blur" }
        ],
        housePercent: [
          { required: true, message: "请输入房屋占比", trigger: "blur" }
        ],
        buildingType: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ],
        buildingStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        buildingName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        principalContactInfo: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],

      },
      // 建筑结构树选项
      buildingOptions: [],
      // 建筑信息数据
      buildings: [],
      // 设备列表
      deviceList: [],
      loginUserBuildingId: this.$store.state.user.buildingId,
      // 地块选项是否可用
      plotAvail: false,
      // 建筑选项是否可用
      louAvail: false,
      // 单元选项是否可用
      unitAvail: false,
      // 层选项是否可用
      layerAvail: false,
      // 房屋选项是否可用
      houseAvail: false,
      expand: [],
      treeNodeList:[]
    };
  },

  watch: {
    '$store.state.app.screenHeight': function () { //监听屏幕高度变化
      if (this.$refs.table.$el.offsetTop) {
        this.tableHeight = window.innerHeight* this.getRatio() - this.$refs.table.$el.offsetTop - 94;
      } else {
        this.tableHeight = window.innerHeight* this.getRatio() - 62 - 92;
      }
    },
    //监听选择上级是楼栋、层数还是单元
    'form.parentId': 'buildingParentIdChange',

  },
  created() {
    this.getList(1);
    this.getTreeselect();
  },
  methods: {
    pointTwo(row){
      if(row.id ==="0"){
        row.aream = null
      }else {
        if(Number(row.aream).toFixed(2)!==0.00){
          return Number(row.aream).toFixed(2)
        }
      }
    },
    buildingParentIdChange() {

    },
    dialogClose() {
      this.plotAvail = false
      this.louAvail = false
      this.unitAvail = false
      this.layerAvail = false
      this.houseAvail = false
    },
    /** 查询建筑信息列表 */
    getList(st) {
      this.loading = true;
      this.queryParams.parentId='0';
      listBuilding(this.queryParams).then(response => {
        this.$nextTick(()=>{
          this.buildingList = this.handleTree(response.rows, "id");
          this.buildingList=[{id: '0',
            aream: null,
            principal:' ',
            principalContactInfo:' ',
            buildingName: "兴筑管理园区",
            buildingType: ' ',
            children: this.buildingList ,
            orderNum:' '}];
          if(st===1){
            this.$nextTick(() => {

            });
          }
          this.loading = false;
        })

      });
    },
    reacquireTreeNodeChildList(parentId){
      const store = this.$refs.table.store;
      const parentTreeNode = store.states.treeData[parentId];
      if(parentTreeNode){
        // 如果该节点已加载
        if (parentTreeNode.loaded) {
          parentTreeNode.loaded=false;
          parentTreeNode.expanded=false;
        }
      }
    },
    buildingListLoad(tree, treeNode, resolve) {
      let queryParams={
        parentId:tree.id
      }
      listBuilding(queryParams).then(response => {
        resolve(response.rows)
      })
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listBuilding({}).then(response => {
        this.buildingOptions = []
        let tenantName = this.$store.getters.buildTreeTopName;
        const build = {id: 0, buildingName: tenantName, children: []};
        build.children = this.handleTree(response.rows, "id");
        this.buildingOptions.push(build);
        this.buildings=response.rows
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.buildingName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        buildingNo: null,
        buildingName: null,
        aream: null,
        parentId: null,
        floorHeight: null,
        buildingType: null,
        buildingStatus: null,
        principal: null,
        principalContactInfo: null,
        ancestors: null,
        tenantId: null,
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.typeFlag=false
      this.statusFlag=false
      this.readOnly=false
      this.parentId=undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    conditionToggle() {
      if (this.$refs['toggle-container'].style.display === 'none') {
        this.$refs['toggle-container'].style.display = 'inline-block';
        this.tableHeight = window.innerHeight* this.getRatio() - this.$refs.table.$el.offsetTop - 92;
      } else {
        this.$refs['toggle-container'].style.display = 'none';
        this.tableHeight = window.innerHeight* this.getRatio() - this.$refs.table.$el.offsetTop - 92;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      //地块只能在根路径下创建 建筑只能在根路径或地块下创建
      if (!row.id){
        this.louAvail = true
        this.plotAvail = true
      }else if(row.buildingType === '0'){
        this.louAvail = true
      }else if(row.buildingType === '1'){
        this.unitAvail = true
      }else if(row.buildingType === '2'){
        this.layerAvail = true
      }else if(row.buildingType === '3'){
        this.houseAvail = true
      }

      this.reset();
      // this.getTreeselect();
      this.dialogClassType='_baseForm_big'
      this.open = true;
      this.readOnly=false
      this.title = "新增建筑信息";
      this.dialogIcon = 'el-icon-plus';
      if(row){
        this.form.parentId = row.id;
      }
      this.operationType = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.open = true;
      this.title = "修改建筑信息";
      this.dialogClassType='_baseForm_big'
      this.dialogIcon = 'el-icon-edit';
      getBuilding(id).then(response => {
        this.form = response.data;
        this.form.aream = this.form.aream.toFixed(2)
        this.parentId=this.form.parentId
        this.getTreeselect();
        this.operationType = 2;
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      this.open = true;
      this.title = "建筑信息详情";
      this.readOnly = true;
      this.dialogClassType='_baseForm_big'
      this.dialogIcon = 'el-icon-view';
      // this.getDeviceByBuildingId(id)
      getBuilding(id).then(response => {
        this.form = response.data;
        this.form.aream = this.form.aream.toFixed(2)
        this.operationType = 3;
        this.getTreeselect();
      });
    },
    /**根据建筑信息获取设备信息*/
    // getDeviceByBuildingId(id){
    //   getDeviceByBuildingId(id).then(res=>{
    //     this.deviceList=res
    //   })
    // },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBuilding(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              if(this.form.parentId==='0'){
                this.getList(1)
              }else {
                this.reacquireTreeNodeChildList(this.form.parentId)
              }
              this.getTreeselect();
            });
          } else {
            //this.form.parentId = this.parentId
            //console.log(this.form.parentId)
            // if(this.form.parentId===null || typeof(this.form.parentId)==="undefined" || this.form.parentId===''){
            //   this.$modal.msgError("上级建筑不能为空")
            //   return
            // }
            addBuilding(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if(this.form.parentId==='0'){
                this.getList(1)
              }else {
                this.reacquireTreeNodeChildList(this.form.parentId)
              }
              this.getTreeselect();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if(row.children){
        if (row.children.length!=0){
          this.$modal.msgError("该信息存在下级，不允许删除")
          return
        }
      }
      this.$modal.confirm('是否确认删除选中的数据的数据项？').then(function () {
        return delBuilding(ids);
      }).then(() => {
        this.getList(1)
        this.$modal.msgSuccess("删除成功");
        this.reacquireTreeNodeChildList(row.parentId);
        this.getTreeselect();
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wyfw/building/export', {
        ...this.queryParams
      }, `building_${new Date().getTime()}.xlsx`)
    },
    //格式化上级
    parentIdFormatter(row){
      for (let build of this.buildings){
        if (build.id===row){
          return build.buildingName
        }
      }
    },
    //设备类型格式化
    typeFormatter(row){
      if(row.deviceType==='1'){
        return '电表'
      }else if (row.deviceType==='2'){
        return '水表'
      }else if(row.deviceType==='3'){
        return '照明'
      }else if (row.deviceType==='4'){
        return '空调'
      }
    }
  },
  mounted() {
    this.$nextTick(function () {
      this.tableHeight = window.innerHeight* this.getRatio() - this.$refs.table.$el.offsetTop - 92;
    });
  },
};
</script>

<style scoped >
/deep/ .vue-treeselect__label{
  font-weight:normal;
}
</style>
